package gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import Simulator.Simulator;
import Visualisation.Visual;

@SuppressWarnings("serial")
public class TrafficGUI extends JFrame implements ActionListener{

	private JTextField textNumCars, textMaxSpeed, textLengthRoad, textNumIterations, textProbability, textIncomingProbability, textOutputFile;
	private JButton simulateButton, selectFileButton;
	private JTextArea log;
	@SuppressWarnings("unused")
	private JFrame frame;

	private int numCars;
	private int maxSpeed;
	private int iterations;
	private int lengthRoad;

	public TrafficGUI(){
		JPanel textPanel = new JPanel();
		textPanel.setLayout(new GridLayout(7,2));
		frame = new JFrame();

		textNumCars = new JTextField(8);
		textNumCars.setText("50");
		textPanel.add(new JLabel("Number of Cars: "));
		textPanel.add(textNumCars);

		textMaxSpeed = new JTextField(8);
		textMaxSpeed.setText("10");
		textPanel.add(new JLabel("Maximum Speed: "));
		textPanel.add(textMaxSpeed);

		textLengthRoad = new JTextField(8);
		textLengthRoad.setText("1000");
		textPanel.add(new JLabel("Length of the road: "));
		textPanel.add(textLengthRoad);

		textNumIterations = new JTextField(8);
		textNumIterations.setText("1000");
		textPanel.add(new JLabel("Number of iterations: "));
		textPanel.add(textNumIterations);

		textProbability = new JTextField(8);
		textProbability.setText("0.7");
		textPanel.add(new JLabel("Probability of reduce speed: "));
		textPanel.add(textProbability);

		textIncomingProbability = new JTextField(8);
		textIncomingProbability.setText("0.8");
		textPanel.add(new JLabel("Incoming Car Probability: "));
		textPanel.add(textIncomingProbability);

		textOutputFile = new JTextField(8);
		textOutputFile.setText("out.dat");
		JPanel outputFilePanel = new JPanel();
		outputFilePanel.setLayout(new GridLayout(0,2));
		outputFilePanel.add(textOutputFile);
		selectFileButton = new JButton("Select");
		selectFileButton.addActionListener(this);
		outputFilePanel.add(selectFileButton);
		textPanel.add(new JLabel("Output Filename: "));
		textPanel.add(outputFilePanel);

		simulateButton = new JButton("Simulate");
		simulateButton.addActionListener(this);

		log = new JTextArea();
		log.setRows(5);

		log.setEditable(false);

		this.add(textPanel,BorderLayout.NORTH);
		this.add(simulateButton,BorderLayout.SOUTH);
		this.add(new JScrollPane(log),BorderLayout.CENTER);

		this.pack();
		this.setVisible(true);
		this.setLocation(100,100);
		this.setTitle("ITB Traffic Simulator - Prototype 1");
	}

	public static void main(String[] args) {
		TrafficGUI gui = new TrafficGUI();
		gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource()==simulateButton){
			if(Float.parseFloat(textIncomingProbability.getText()) >= 0 & Float.parseFloat(textIncomingProbability.getText()) <= 1){
				if(Float.parseFloat(textProbability.getText()) >= 0 & Float.parseFloat(textProbability.getText()) <= 1){
					if(Integer.parseInt(textLengthRoad.getText()) <= 1400){
						if(Integer.parseInt(textNumCars.getText()) < Integer.parseInt(textLengthRoad.getText())/1.25){
							log.append("Starting Simulation");

						numCars = Integer.parseInt(textNumCars.getText());
						maxSpeed = Integer.parseInt(textMaxSpeed.getText());
						iterations = Integer.parseInt(textNumIterations.getText());
						lengthRoad = Integer.parseInt(textLengthRoad.getText());
						float probability;
						float incomingCarProbability;


						probability = Float.parseFloat(textProbability.getText());
						incomingCarProbability = Float.parseFloat(textIncomingProbability.getText());
						String filename = textOutputFile.getText();

						Simulator simulator = new Simulator(numCars,maxSpeed,lengthRoad,probability, incomingCarProbability);

						// Set output file
						PrintWriter outFile = simulator.printToFile(filename);

						simulator.simulate(iterations);

						// close output file
						outFile.close();
						simulator.generateGnuplotScript(filename+ ".script", filename);
						log.append("\nDONE, check output file "+filename+",\nand load script file in gnuplot\n");

						try {
							Visual test = new Visual();

							test.start();
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}else if(e.getSource()==selectFileButton){
						JFileChooser fc = new JFileChooser();			
						int returnVal = fc.showSaveDialog(this);
						if (returnVal == JFileChooser.APPROVE_OPTION) {
							textOutputFile.setText(fc.getSelectedFile().getAbsolutePath());;
						}
					}
				
					else JOptionPane.showMessageDialog(new JFrame(), 
							"you have excided the maximum number of cars over the length of the road", "Input Error",
							JOptionPane.ERROR_MESSAGE);	
				}else JOptionPane.showMessageDialog(new JFrame(), 
						"You have excided the maximum road length of 1000", "Input Error",
						JOptionPane.ERROR_MESSAGE);	

			}
			else JOptionPane.showMessageDialog(new JFrame(), 
					"Probability to reduce speed must be greater or equal to zero or less or equal to 1", "Input Error",
					JOptionPane.ERROR_MESSAGE);				        
		}
		else JOptionPane.showMessageDialog(new JFrame(), 
				"Incoming Car Probability must be greater or equal to zero or less or equal to 1", "Input Error",
				JOptionPane.ERROR_MESSAGE);
		}
	}
}
